package com.atguigu.chap07;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 案例：
 *      生产者消费者 线程间通信
 *      生产10个馒头，消费10个馒头。同一时刻最多只能生产3个馒头。
 */
public class BlockingQueueDemo2 {

    public static void main(String[] args) {
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(3);  //最多生产三个馒头。队列最大容量3

        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    blockingQueue.put(i);
                    System.out.println(Thread.currentThread().getName() + "\t" + "---生成第["+i+"]个馒头,剩余馒头="+blockingQueue.size());
                    Thread.sleep(2000); //2000毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者").start();


        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    //开始消费馒头
                    Integer mantou = blockingQueue.take();
                    System.out.println(Thread.currentThread().getName() + "\t" + "======================消费第["+mantou+"]个馒头,剩余馒头="+blockingQueue.size());
                    Thread.sleep(3000); //3000毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者").start();
    }
}
